/*
 * MainForm.java
 *
 * Created on March 20, 2006, 9:23 AM
 */

/**
 *
 * @author  Sujal Bista
 */

import net.java.games.jogl.*;
import java.awt.BorderLayout;
import javax.swing.*;
import java.lang.Thread;
import java.lang.Runnable;
import java.util.Vector;
import java.lang.reflect.Array;
import java.util.HashSet;
import java.sql.SQLException;
import java.lang.Integer;
import java.lang.Math;


public class MainForm extends javax.swing.JFrame {
    
    GLCanvas canvas; // drawable in a frame
    showOutput output;
    tcpServer server;
    Database database;
    Summary finalSummary;
    Thread drawingThread;
    opengl openglClass;

    /** Creates new form MainForm */
    public MainForm(){

        //set popup to false
        globalData.initGlobalData();
        JPopupMenu.setDefaultLightWeightPopupEnabled(false);
        initDatabase();
        initComponents();
        initOpengl();
        initSoftware();
        
        if(globalData.JudgeATimeRangeInSec==3)
            JudgeATimerM.setSelected(true);
        else
            JudgeATimerM.setSelected(false);
        
        output=new showOutput(null);
        server=new tcpServer(output);

        server.start();
        
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        jPanel3 = new javax.swing.JPanel();
        jLabel3 = new javax.swing.JLabel();
        GroupGenderC = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();
        EventC = new javax.swing.JComboBox();
        jLabel2 = new javax.swing.JLabel();
        AthleteC = new javax.swing.JComboBox();
        MainP = new javax.swing.JPanel();
        StartB = new javax.swing.JButton();
        StopB = new javax.swing.JButton();
        jPanel5 = new javax.swing.JPanel();
        GetScoresB = new javax.swing.JButton();
        jPanel7 = new javax.swing.JPanel();
        EnterScore = new javax.swing.JButton();
        jPanel6 = new javax.swing.JPanel();
        ShowB = new javax.swing.JButton();
        jPanel4 = new javax.swing.JPanel();
        ResetB = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        PublishB = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jTextArea1 = new javax.swing.JTextArea();
        Head1 = new javax.swing.JTextArea();
        HeadScore = new javax.swing.JTextField();
        jSeparator1 = new javax.swing.JSeparator();
        Head2 = new javax.swing.JTextArea();
        HeadDeduction = new javax.swing.JTextField();
        Head3 = new javax.swing.JTextArea();
        Reason = new javax.swing.JTextField();
        HeadSubmitB = new javax.swing.JButton();
        HeadUndoB = new javax.swing.JButton();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        ExitM = new javax.swing.JMenuItem();
        jMenu2 = new javax.swing.JMenu();
        JudgeATimerM = new javax.swing.JCheckBoxMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Wushu Judging");
        setMinimumSize(new java.awt.Dimension(1024, 104));
        setName("MainFrame"); // NOI18N
        getContentPane().setLayout(new java.awt.GridBagLayout());

        jPanel3.setMinimumSize(new java.awt.Dimension(1324, 33));
        jPanel3.setPreferredSize(new java.awt.Dimension(1024, 32));
        jPanel3.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT));

        jLabel3.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel3.setText("Age/Experience/Gender");
        jPanel3.add(jLabel3);

        GroupGenderC.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        GroupGenderC.setPreferredSize(new java.awt.Dimension(250, 22));
        GroupGenderC.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                GroupGenderCActionPerformed(evt);
            }
        });
        jPanel3.add(GroupGenderC);

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel1.setText("Event");
        jPanel3.add(jLabel1);

        EventC.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        EventC.setEnabled(false);
        EventC.setPreferredSize(new java.awt.Dimension(250, 22));
        EventC.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                EventCActionPerformed(evt);
            }
        });
        jPanel3.add(EventC);

        jLabel2.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel2.setText("Athlete");
        jPanel3.add(jLabel2);

        AthleteC.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        AthleteC.setEnabled(false);
        AthleteC.setPreferredSize(new java.awt.Dimension(250, 22));
        AthleteC.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                AthleteCActionPerformed(evt);
            }
        });
        jPanel3.add(AthleteC);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        getContentPane().add(jPanel3, gridBagConstraints);

        MainP.setMaximumSize(new java.awt.Dimension(32767, 34));
        MainP.setPreferredSize(new java.awt.Dimension(407, 33));
        MainP.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT));

        StartB.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        StartB.setText("Start (1)");
        StartB.setEnabled(false);
        StartB.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                StartBActionPerformed(evt);
            }
        });
        MainP.add(StartB);

        StopB.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        StopB.setText("Stop (2)");
        StopB.setEnabled(false);
        StopB.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                StopBActionPerformed(evt);
            }
        });
        MainP.add(StopB);

        jPanel5.setPreferredSize(new java.awt.Dimension(20, 10));
        jPanel5.setRequestFocusEnabled(false);
        MainP.add(jPanel5);

        GetScoresB.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        GetScoresB.setText("Scores Received (3)");
        GetScoresB.setEnabled(false);
        GetScoresB.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                GetScoresBActionPerformed(evt);
            }
        });
        MainP.add(GetScoresB);

        jPanel7.setPreferredSize(new java.awt.Dimension(20, 10));
        jPanel7.setRequestFocusEnabled(false);
        MainP.add(jPanel7);

        EnterScore.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        EnterScore.setText("Modify Score (3.5)");
        EnterScore.setEnabled(false);
        EnterScore.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                EnterScoreActionPerformed(evt);
            }
        });
        MainP.add(EnterScore);

        jPanel6.setPreferredSize(new java.awt.Dimension(20, 10));
        jPanel6.setRequestFocusEnabled(false);
        MainP.add(jPanel6);

        ShowB.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        ShowB.setText("Show & Save (4)");
        ShowB.setEnabled(false);
        ShowB.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ShowBActionPerformed(evt);
            }
        });
        MainP.add(ShowB);

        jPanel4.setPreferredSize(new java.awt.Dimension(80, 10));
        MainP.add(jPanel4);

        ResetB.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        ResetB.setText("Reset");
        ResetB.setEnabled(false);
        ResetB.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ResetBActionPerformed(evt);
            }
        });
        MainP.add(ResetB);

        jPanel1.setPreferredSize(new java.awt.Dimension(40, 10));
        jPanel1.setRequestFocusEnabled(false);
        MainP.add(jPanel1);

        PublishB.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        PublishB.setText("Publish");
        PublishB.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                PublishBActionPerformed(evt);
            }
        });
        MainP.add(PublishB);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        gridBagConstraints.weightx = 1.0;
        getContentPane().add(MainP, gridBagConstraints);

        jPanel2.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jTextArea1.setEditable(false);
        jTextArea1.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        jTextArea1.setText("Head Judge:      ");
        jTextArea1.setFocusable(false);
        jTextArea1.setPreferredSize(new java.awt.Dimension(110, 22));
        jPanel2.add(jTextArea1, new org.netbeans.lib.awtextra.AbsoluteConstraints(5, 7, -1, -1));

        Head1.setEditable(false);
        Head1.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        Head1.setText(" Overall Score");
        Head1.setEnabled(false);
        Head1.setFocusable(false);
        Head1.setPreferredSize(new java.awt.Dimension(114, 22));
        jPanel2.add(Head1, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 7, -1, -1));

        HeadScore.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        HeadScore.setText("0.0");
        HeadScore.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED));
        HeadScore.setEnabled(false);
        HeadScore.setPreferredSize(new java.awt.Dimension(60, 20));
        jPanel2.add(HeadScore, new org.netbeans.lib.awtextra.AbsoluteConstraints(239, 8, -1, -1));

        jSeparator1.setEnabled(false);
        jSeparator1.setPreferredSize(new java.awt.Dimension(50, 2));
        jPanel2.add(jSeparator1, new org.netbeans.lib.awtextra.AbsoluteConstraints(304, 17, -1, -1));

        Head2.setEditable(false);
        Head2.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        Head2.setText("Deductions");
        Head2.setEnabled(false);
        Head2.setFocusable(false);
        jPanel2.add(Head2, new org.netbeans.lib.awtextra.AbsoluteConstraints(359, 5, -1, -1));

        HeadDeduction.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        HeadDeduction.setForeground(new java.awt.Color(255, 0, 0));
        HeadDeduction.setText("0.0");
        HeadDeduction.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED));
        HeadDeduction.setEnabled(false);
        HeadDeduction.setPreferredSize(new java.awt.Dimension(60, 20));
        jPanel2.add(HeadDeduction, new org.netbeans.lib.awtextra.AbsoluteConstraints(455, 8, -1, -1));

        Head3.setEditable(false);
        Head3.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        Head3.setText("Reason");
        Head3.setEnabled(false);
        Head3.setFocusable(false);
        jPanel2.add(Head3, new org.netbeans.lib.awtextra.AbsoluteConstraints(520, 5, -1, -1));

        Reason.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        Reason.setForeground(new java.awt.Color(255, 0, 0));
        Reason.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED));
        Reason.setEnabled(false);
        Reason.setPreferredSize(new java.awt.Dimension(150, 20));
        jPanel2.add(Reason, new org.netbeans.lib.awtextra.AbsoluteConstraints(586, 8, -1, -1));

        HeadSubmitB.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        HeadSubmitB.setText("Submit");
        HeadSubmitB.setEnabled(false);
        HeadSubmitB.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                HeadSubmitBActionPerformed(evt);
            }
        });
        jPanel2.add(HeadSubmitB, new org.netbeans.lib.awtextra.AbsoluteConstraints(741, 6, -1, -1));

        HeadUndoB.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        HeadUndoB.setText("Undo");
        HeadUndoB.setEnabled(false);
        HeadUndoB.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                HeadUndoBActionPerformed(evt);
            }
        });
        jPanel2.add(HeadUndoB, new org.netbeans.lib.awtextra.AbsoluteConstraints(811, 6, -1, -1));

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 5;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.SOUTHWEST;
        getContentPane().add(jPanel2, gridBagConstraints);

        jMenu1.setText("File");

        ExitM.setText("Exit");
        ExitM.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ExitMActionPerformed(evt);
            }
        });
        jMenu1.add(ExitM);

        jMenuBar1.add(jMenu1);

        jMenu2.setText("Options");

        JudgeATimerM.setSelected(true);
        JudgeATimerM.setText("EnableAJudgeTimer");
        JudgeATimerM.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                JudgeATimerMActionPerformed(evt);
            }
        });
        jMenu2.add(JudgeATimerM);

        jMenuBar1.add(jMenu2);

        setJMenuBar(jMenuBar1);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void PublishBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_PublishBActionPerformed
        Publisher pub3 = new Publisher("..\\Data\\Scores.html");
        pub3.publishScores(database);
    }//GEN-LAST:event_PublishBActionPerformed

    private void GroupGenderCActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_GroupGenderCActionPerformed

        //set current gender and group
        closeAthlete();
        String groupGender = (String) GroupGenderC.getSelectedItem();
        
        //code changed it handles all cases
        if(groupGender.length()!=0)
        {
            globalData.currentAge=groupGender.substring(0, groupGender.indexOf('/'));//.toLowerCase();
            groupGender=groupGender.substring(groupGender.indexOf('/')+1, groupGender.length());
            globalData.currentGroup=groupGender.substring(0, groupGender.indexOf('/'));//.toLowerCase();
            globalData.currentGender=groupGender.substring(groupGender.indexOf('/')+1, groupGender.length());//.toLowerCase();
        }
        
        // Clear event and athlete box
        EventC.removeAllItems();
        EventC.setEnabled(false);
        globalData.currentEvent = null;
        AthleteC.removeAllItems();
        AthleteC.setEnabled(false);
        
        // Load contents of event box
        HashSet validEvents = database.getEvents(globalData.currentAge,globalData.currentGroup, globalData.currentGender);
        
        int i;
        if (validEvents != null) {
            EventC.addItem(globalData.eventInfo[0]);
            globalData.eventCount = 0;
            for (i = 0; i < Array.getLength(globalData.eventInfo); i++) {
                if (validEvents.contains(globalData.eventInfo[i])) 
                {
                    EventC.addItem(globalData.eventInfo[i]);
                    EventC.setEnabled(true);
                    globalData.eventCount++;
                }
            }

        }
        //just load the data to thet screen
        showSummary(false);
    }//GEN-LAST:event_GroupGenderCActionPerformed

    private void HeadSubmitBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_HeadSubmitBActionPerformed

        headJudgeSubmitAction();
    }//GEN-LAST:event_HeadSubmitBActionPerformed

    private void HeadUndoBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_HeadUndoBActionPerformed

        headJudgeUndoAction();
    }//GEN-LAST:event_HeadUndoBActionPerformed

    private void GetScoresBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_GetScoresBActionPerformed

        freezeAthlete();
    }//GEN-LAST:event_GetScoresBActionPerformed

    private void ResetBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ResetBActionPerformed
        if(JOptionPane.showConfirmDialog(null, "Do you want to reset the athlete?" , "Request Confirmation", JOptionPane.YES_NO_OPTION)==JOptionPane.NO_OPTION)
            return;
        
        //reset the data related to the athlete
        database.resetNSave(globalData.currentAthlete);
        
        //close the athlete
        closeAthlete();
        
        //reopen the athlete
        openAthlete();
        
        //set  appopriate buttons
        StartB.setEnabled(true);
        ResetB.setEnabled(false);
    }//GEN-LAST:event_ResetBActionPerformed

    private void AthleteCActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AthleteCActionPerformed
        //closes any active athlete if any

        closeAthlete();

        if (AthleteC.getSelectedItem() != null && !((String) AthleteC.getSelectedItem()).equals(""))
            openAthlete();
        
        showSummary(false);
        
        
        
    }//GEN-LAST:event_AthleteCActionPerformed

    private void ShowBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ShowBActionPerformed
        
        //save the data to the database
        database.Marshal(globalData.currentAthlete,globalData.scoringSystem);
        
        //show output to the projector screen
        showSummary(globalData.displayScore);    

                //enable reset athlete button
        ResetB.setEnabled(true);
        
        //other enable buttons
        GroupGenderC.setEnabled(true);
        EventC.setEnabled(true);
        AthleteC.setEnabled(true);
        EnterScore.setEnabled(false);

        //head judge buttons and fields should be disabled
        Head1.setEnabled(false);
        HeadScore.setEnabled(false);
        HeadScore.setText("0.0");
        Head2.setEnabled(false);
        HeadDeduction.setEnabled(false);
        HeadDeduction.setText("0.0");
        Head3.setEnabled(false);
        Reason.setEnabled(false);
        Reason.setText("");
        HeadSubmitB.setEnabled(false);
        HeadUndoB.setEnabled(false);
        
    }//GEN-LAST:event_ShowBActionPerformed

    private void StopBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_StopBActionPerformed
        stopAthlete();
    }//GEN-LAST:event_StopBActionPerformed

    private void EventCActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_EventCActionPerformed
        loadEvent();
    }//GEN-LAST:event_EventCActionPerformed
   
    private void StartBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_StartBActionPerformed
        startAthlete();
    }//GEN-LAST:event_StartBActionPerformed

    private void ExitMActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ExitMActionPerformed
        System.exit(0);
    }//GEN-LAST:event_ExitMActionPerformed

    private void EnterScoreActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_EnterScoreActionPerformed

        //only allow manual entry for the traditional system
        //if(globalData.scoringSystem!=0)
        //    return;

        ManualEntryForum manualEntryForum=new ManualEntryForum(this,true);

        /////////////////////////////////////////////////////////////////////////////////////////
        //upload data to the forum
        String eventName=globalData.currentAge+" "+globalData.currentGroup + " " + globalData.currentGender+" "+globalData.currentEvent.getevent();
        manualEntryForum.setEvent(eventName);

        //set parameters
        if (globalData.currentAthlete != null)
        {
            String temp = globalData.currentAthlete.getName();
            String name = temp.substring(0, temp.lastIndexOf('(') - 1);
            manualEntryForum.setName(name);

            int j;
            
            for(j=0;j<(globalData.totalJudges-1);j++)
            {
                manualEntryForum.setScore(j,"");
                //judge type A
                if(globalData.currentAthlete.getJudgeType(j)==judge.judgeType.judgeA)
                {
                    //for judgeA (x=time in millisec, y=code)
                    String judgeString=new String();
                    for(int i=0;i<globalData.currentAthlete.getJudgeVector(j).size();i++)
                    {
                        point p=(point)globalData.currentAthlete.getJudgeVector(j).elementAt(i);
                        judgeString+="("+(p.x/1000.0)+":"+p.y+"),";
                    }
                    manualEntryForum.setScore(j,judgeString);
                }
                else if(globalData.currentAthlete.getJudgeType(j)==judge.judgeType.judgeB) //judge type B
                {
                    //for judgeB (x=score,y=0)
                    float currScore=0.0f;
                    int i=globalData.currentAthlete.getJudgeVector(j).size()-1;
                    if(i>=0)
                    {
                        point p=(point)globalData.currentAthlete.getJudgeVector(j).elementAt(i);
                        currScore=p.x;
                    }
                    if(currScore==0.0)
                        manualEntryForum.setScore(j,"");
                    else
                        manualEntryForum.setScore(j,""+currScore);
                }
                else if(globalData.currentAthlete.getJudgeType(j)==judge.judgeType.judgeC) //judge type C
                {
                    //for judgeC (x=+100 for new nandu, +50 for connected one,y= (0:=fail 1:=true) )
                    String judgeString=new String();
                    for(int i=0;i<globalData.currentAthlete.getJudgeVector(j).size();i++)
                    {
                        point p=(point)globalData.currentAthlete.getJudgeVector(j).elementAt(i);
                        judgeString+="("+p.x+":"+p.y+"),";
                    }
                    manualEntryForum.setScore(j,judgeString);
                }
                
            }
        }
        /////////////////////////////////////////////////////////////////////////////////////////

        //make the forum visible
        manualEntryForum.setVisible(true);

        /////////////////////////////////////////////////////////////////////////////////////////
        //upload data to the forum

        if(manualEntryForum.SaveClicked())
        {
            globalData.currentAthlete.clearJudgesVector(true);
            //add the new data
            for(int j=0;j<(globalData.totalJudges-1);j++)
            {
                //judge type A
                if(globalData.currentAthlete.getJudgeType(j)==judge.judgeType.judgeA)
                {
                    //for judgeA (x=time in millisec, y=code)
                    String judgeData=manualEntryForum.getJudgeString(j);
                    String value="";
                    int count=0;

                    while(judgeData.length()!=0)
                    {
                        if(judgeData.indexOf(",")==-1)
                        {
                            value=judgeData;
                            judgeData="";
                        }
                        else
                        {
                           value=judgeData.substring(0, judgeData.indexOf(","));
                           judgeData=judgeData.substring(judgeData.indexOf(",")+1);
                        }
                        String timeInSec=value.substring(1, value.indexOf(":"));
                        String code=value.substring(value.indexOf(":")+1,value.indexOf(")"));
                        int timeInSecInt=0;
                        int codeInt=0;
                        try
                        {
                            timeInSecInt = (int)(Float.parseFloat(timeInSec)*1000);
                            codeInt = (int)(Float.parseFloat(code));
                        } catch (NumberFormatException e)
                        {
                           
                        }
                        globalData.currentAthlete.addJudgeData(j,new point(timeInSecInt,codeInt));
                        count++;
                    }
                }
                else if(globalData.currentAthlete.getJudgeType(j)==judge.judgeType.judgeB) //judge type B
                {
                    //for judgeB (x=score,y=0)
                    float score=manualEntryForum.getScore(j);
                    if(score!=0)
                    {
                        globalData.currentAthlete.addJudgeData(j,new point(score,0));
                        globalData.currentAthlete.setJudgeConnected(j, true);
                        globalData.currentAthlete.setJudgeType(j, judge.judgeType.judgeB);
                    }

                }
                else if(globalData.currentAthlete.getJudgeType(j)==judge.judgeType.judgeC) //judge type C
                {
                    //for judgeC (x=+100 for new nandu, +50 for connected one,y= (0:=fail 1:=true) )
                    String judgeData=manualEntryForum.getJudgeString(j);
                    String value="";
                    int count=0;

                    while(judgeData.length()!=0)
                    {
                        if(judgeData.indexOf(",")==-1)
                        {
                            value=judgeData;
                            judgeData="";
                        }
                        else
                        {
                           value=judgeData.substring(0, judgeData.indexOf(","));
                           judgeData=judgeData.substring(judgeData.indexOf(",")+1);
                        }
                        String position=value.substring(1, value.indexOf(":"));
                        String code=value.substring(value.indexOf(":")+1,value.indexOf(")"));
                        int positionInt=0;
                        int codeInt=0;
                        try
                        {
                            positionInt = (int)(Float.parseFloat(position));
                            codeInt = (int)(Float.parseFloat(code));
                        } catch (NumberFormatException e)
                        {
                           
                        }
                        globalData.currentAthlete.addJudgeData(j,new point(positionInt,codeInt));
                        count++;
                    }
                }

            }
            
            /////////////////////////////////////////////////////////////////////////////////////////
            //from freezeAthlete
            //disable buttons
            GetScoresB.setEnabled(false);
            //enable buttons
            ShowB.setEnabled(true);
            if(globalData.scoringSystem==0)
                EnterScore.setEnabled(true);

            /*
            //enable head judge buttons and fields
            Head1.setEnabled(true);
            HeadScore.setEnabled(true);
            Head2.setEnabled(true);
            HeadDeduction.setEnabled(true);
            Head3.setEnabled(true);
            Reason.setEnabled(true);
            HeadSubmitB.setEnabled(true);
            */
            // unset athlete's scorable status
            globalData.athleteScorable = false;
            /////////////////////////////////////////////////////////////////////////////////////////
        }
        /////////////////////////////////////////////////////////////////////////////////////////


        
        

    }//GEN-LAST:event_EnterScoreActionPerformed

    private void JudgeATimerMActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JudgeATimerMActionPerformed
        if(JudgeATimerM.isSelected())
            globalData.JudgeATimeRangeInSec=3;
        else
            globalData.JudgeATimeRangeInSec=4000;
            
    }//GEN-LAST:event_JudgeATimerMActionPerformed
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new MainForm().setVisible(true);
            }
        });
    }
    
    // sets up database
    void initDatabase()
    {
        try {
            database=new Database();
        } catch (Exception e) {
            System.err.println(e);
            System.exit(1);
        }
    }
    //sets up opengl
    void initOpengl()
    {
        //this.setSize(1024,768);
        this.setSize(900,768);
              
        //specify a drawable: canvas
        GLCapabilities capabilities = new GLCapabilities();
        canvas = GLDrawableFactory.getFactory().createGLCanvas(capabilities);

        canvas.setIgnoreRepaint(true);

        //main opengl drawing class
        openglClass=new opengl();
        
        //listen to the events related to canvas: reshape
        canvas.addGLEventListener(openglClass);
        //add the canvas to fill the Frame container
        

        java.awt.GridBagConstraints gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.gridheight = 3;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        gridBagConstraints.weightx = 0.1;
        gridBagConstraints.weighty = 1.0;
        getContentPane().add(canvas, gridBagConstraints);
       
        Runnable runnable = new Runnable() {
            public void run() {
                while (true) {
                   canvas.display();
                   try {
                       Thread.sleep(50);
                   } catch (InterruptedException e) {}
                }
            }
        };
        drawingThread = new Thread(runnable);
        drawingThread.start();
       
    }
    
    void initSoftware()
    {
        HashSet groupList=database.getGroups();
        for (int i = 0; i < Array.getLength(globalData.groupInfo); i++)
        {
            if(groupList.contains(globalData.groupInfo[i]))
                GroupGenderC.addItem(globalData.groupInfo[i]);
        }
        
        showSummary(false);
    }

    private void loadEvent()
    {
        //close open athlete if any
        closeAthlete();

        //remove all athlete list from the drop down list
        AthleteC.removeAllItems();
        AthleteC.setEnabled(false);

        //set current event on the global pointer
        globalData.currentEvent = new event();
        globalData.currentEvent.setevent((String)EventC.getSelectedItem());


        if (globalData.currentEvent.getevent() == null)
        {
            return;
        }

        // get athlete list from database
        Vector athletes = null;


        //save old scoring system
        int oldScoringSystem=globalData.scoringSystem;

        //get the type of the scoring sytem used
        if(globalData.currentGroup.length()>0 && globalData.currentEvent.getevent().length()>0)
            globalData.scoringSystem=database.getScoringSystem(globalData.currentGroup,globalData.currentEvent.getevent());
        else
            globalData.scoringSystem=2;

        //if the scoring system changed
        if(globalData.scoringSystem!=oldScoringSystem || globalData.getUserAdded())
        {
            //send data to all the judges
            for(int i=0;i<(globalData.totalJudges-1);i++)
            {
                // If the client is connected, then you can erase its data...
                if(globalData.isJudgeConnected(i)==true)
                {
                    globalData.clients[i].sendMessage("SCOR "+ globalData.scoringSystem);
                }
                else
                {
                    if(globalData.scoringSystem==0) //traditional
                        globalData.judges[i].setType(judge.judgeType.judgeB);
                }
            }
            //set the user added flag to false as the processing is done
            globalData.setUserAdded(false);
        }
        




        //reset graphical interface
        openglClass.resetJudgingScreen();

        //get the poingter to the current athletes based on group,gender and event
        athletes = database.getAthletes(globalData.currentAge, globalData.currentGroup, globalData.currentGender, globalData.currentEvent.getevent());

        if (athletes != null && athletes.size() > 0)
        {
            // enable athlete combo box
            AthleteC.setEnabled(true);
            int i;
            AthleteC.addItem("");

            //load names of all the athletes
            for (i = 0; i < athletes.size(); i++)
            {
                String athlete_name = (String) athletes.get(i);
                AthleteC.addItem(athlete_name);
            }
        }

        showSummary(false);
    }
    
    //all the necessary action to open the athlete
    void openAthlete() 
    {
        globalData.setLock();
        
        //get the name of the selected athlete
        String name = (String) AthleteC.getSelectedItem();
        //use the name along with event, gender info to create athlete in memory
        globalData.currentAthlete = new athlete(globalData.currentGroup, globalData.currentGender,globalData.currentEvent.getevent(), name);

        //retrive the value of current athlete in that event if any
        database.Unmarshal(globalData.currentAthlete);
        
        //set the global time
        globalData.diffTime = globalData.currentAthlete.getTime();
        
        // fill in head-judge data
        if (globalData.currentAthlete.getJudgeVector(globalData.totalJudges-1) != null)
        {
            Vector data = globalData.currentAthlete.getJudgeVector(globalData.totalJudges-1);
            
            //set score given by head judge
            if (data.size() >= 1) 
                HeadScore.setText(String.format("%.2f", (Double) (data.elementAt(0))));

            //set deduction if any
            if (data.size() >= 2) 
                HeadDeduction.setText(String.format("%.2f", (Double) (data.elementAt(1))));
            
            //set reason for duductions if any
            if (globalData.currentAthlete.getReason() != null && globalData.currentAthlete.getReason().length() > 0)
                Reason.setText(globalData.currentAthlete.getReason());

        }
          
        //load up information in screen
        //it will not show projector information
        showSummary(false);
        
        //check if the reset button should be enabled based on if the athlete has 
        //competed in that event before
        if (globalData.currentAthlete.hasCompeted() == false)
        {
            StartB.setEnabled(true);
            ResetB.setEnabled(false);
        }
        else 
        {
            StartB.setEnabled(false);
            ShowB.setEnabled(true);
            EnterScore.setEnabled(false);
            ResetB.setEnabled(true);
        }
        globalData.releaseLock();
    }
    
    void startAthlete() 
    {
        //disable buttons
        GroupGenderC.setEnabled(false);
        EventC.setEnabled(false);
        AthleteC.setEnabled(false);
        StartB.setEnabled(false);

        //enable stop button
        StopB.setEnabled(true);
     
        //record currned time
        globalData.startTime=System.currentTimeMillis();
        globalData.endTime=System.currentTimeMillis();
        globalData.currentAthlete.setSetupInfo(globalData.getSetupInfo());


        if( globalData.currentAthlete.hasCompeted()==false)
        {
            //set the judge type
            for(int i=0;i<globalData.totalJudges;i++)
            {
                globalData.currentAthlete.setJudgeConnected(i,globalData.judgesConnected[i]);
                globalData.currentAthlete.setJudgeType(i,globalData.judges[i].type);
            }
        }

        //get the index of athlete and event
        int eventIndex=EventC.getSelectedIndex();
        int athleteIndex=AthleteC.getSelectedIndex();
        
        
        for(int i=0;i<(globalData.totalJudges-1);i++)
        {
            // If the client is connected, then you can erase its data...
            if(globalData.isJudgeConnected(i)==true) 
            {   
                //debug info written to the text file
                globalData.judges[i].beginAthlete(globalData.currentAthlete.getName());
                
                //load an athlete and send its info to the corresponding judge
                globalData.clients[i].sendMessage("ATHL "+ globalData.scoringSystem +" " +globalData.currentAthlete.toString());
                globalData.clients[i].sendMessage("EVNT "+ globalData.currentGroup + " "
                                                         + globalData.currentGender + " "
                                                         + globalData.currentEvent.getevent());
                globalData.clients[i].individiualDifficultyJudged=0;
                globalData.clients[i].location=0;
            }
        }
        
        globalData.athleteActive=true;
        globalData.athleteScorable = true;
    }
    
    //actions for stopping timing, but still allowing judges to
    //entering their scores
    void stopAthlete() 
    {
        if (globalData.athleteActive) 
        {
            //disable buttons
            StopB.setEnabled(false);
            
            //enable buttons
            GetScoresB.setEnabled(true);
                        
            //unset athlete's active status
            globalData.athleteActive = false;
            
            //record the ending time
            globalData.endTime = System.currentTimeMillis();
        }
    }
    
    void freezeAthlete() 
    {
        // send stop message to clients
        for (int i = 0; i < (globalData.totalJudges-1); i++) 
        {
            if (globalData.isJudgeConnected(i)==true)
            {
                globalData.clients[i].sendMessage("ATST");
            }
        }
        //disable buttons
        GetScoresB.setEnabled(false);
        
        //enable buttons
        ShowB.setEnabled(true);
        //if(globalData.scoringSystem==0)
        if(globalData.enableModifyScore)
            EnterScore.setEnabled(true);
        // enable head judge buttons and fields
        Head1.setEnabled(true);
        HeadScore.setEnabled(true);
        Head2.setEnabled(true);
        HeadDeduction.setEnabled(true);
        Head3.setEnabled(true);
        Reason.setEnabled(true);
        HeadSubmitB.setEnabled(true);
        
        // unset athlete's scorable status
        globalData.athleteScorable = false;
    }
    //checks if the score is in valid range
    private boolean ValidRange(String scoreString)
    {
        double score = Double.parseDouble(scoreString);
        return ValidRange(score);
    }
    
    //checks if the score is in valid range
    private boolean ValidRange(double score)
    {
        if(globalData.scoringSystem==0)    //Traditional system
            return(0.0<=score && score<=10.0);
        else if(globalData.scoringSystem==1)// Nandu AB compulsory
            return (0 <= score  && score <= 5);
        return (0 <= score  && score <= 3); //Nandu ABC
    }
    
    //returns the valid range
    private String getValidRangeString()
    {
        String range="Valid range : ";
        // 0 Traditional System
        if(globalData.scoringSystem==0)//Traditional system
            range=range+"[ 0.0 - 10.0]";
        else if(globalData.scoringSystem==1)// Nandu AB compulsory
            range=range+"[ 0.0 - 5.0]";
        else
             range=range+"[ 0.0 - 3.0]";//Nandu ABC
        return range;
    }
    
    

    //Pefromed when head judge hits submit
    void headJudgeSubmitAction() 
    {
        Vector data = new Vector();

        try 
        {
            double temp_score = Double.parseDouble(HeadScore.getText());
            double temp_deduct = Double.parseDouble(HeadDeduction.getText());
 
            // bad score
            if (temp_score!=0 && !ValidRange(temp_score)) 
            {
                JOptionPane.showMessageDialog(null, "Please enter valid score range. " + getValidRangeString(), "Error", JOptionPane.OK_OPTION);
                HeadScore.grabFocus();
                return;
            }
            
            if (temp_deduct < 0)
            {
                JOptionPane.showMessageDialog(null, "Please enter positive deduction value" , "Error", JOptionPane.OK_OPTION);
                HeadDeduction.grabFocus();
                return;
            }
            
            // bad deduction, needs a reason if > 0
            if ((temp_deduct > 0 && (Reason.getText() == null || Reason.getText().length() <= 0))) 
            {
                JOptionPane.showMessageDialog(null, "Please enter reason for the deduction" , "Error", JOptionPane.OK_OPTION);
                Reason.grabFocus();
                return;
            }
 
        } catch (NumberFormatException e) 
        {
             //show the error
            JOptionPane.showMessageDialog(null, "Head Judge Submition failed. Please enter 0.0 in score/deduct if no values are to be entered" , "Error", JOptionPane.OK_OPTION);
            return;
        }
        //copy the data to athlete pointer
        data.addElement(Double.parseDouble(HeadScore.getText()));
        data.addElement(Double.parseDouble(HeadDeduction.getText()));
        globalData.currentAthlete.setJudgeVector(globalData.totalJudges-1,data);
        globalData.currentAthlete.setReason(Reason.getText());
        
        // disable buttons
        Head1.setEnabled(false);
        HeadScore.setEnabled(false);
        Head2.setEnabled(false);
        HeadDeduction.setEnabled(false);
        Head3.setEnabled(false);
        Reason.setEnabled(false);
        HeadSubmitB.setEnabled(false);
        
        // enable buttons
        HeadUndoB.setEnabled(true);
    }
    
    //undo button hit by head judge
    void headJudgeUndoAction() 
    {
        Vector temp=new Vector();
        globalData.currentAthlete.setJudgeVector(globalData.totalJudges-1,temp);
        
        // disable buttons
        HeadUndoB.setEnabled(false);
        
        // enable buttons
        Head1.setEnabled(true);
        HeadScore.setEnabled(true);
        Head2.setEnabled(true);
        HeadDeduction.setEnabled(true);
        Head3.setEnabled(true);
        Reason.setEnabled(true);
        HeadSubmitB.setEnabled(true);
    }
    
    //all the necessary action to close the athlete
    void closeAthlete() 
    {
        
        //check if any athletes are open
        if (globalData.currentAthlete == null) 
            return;
        
        
            
        //send close athlete data to all of the connecting judges
        for(int i=0;i<(globalData.totalJudges-1);i++) 
        {
            if(globalData.isJudgeConnected(i)==true)
            {
                globalData.judges[i].endAthlete();
                globalData.clients[i].sendMessage("ATFN");
            }
        }
        globalData.setLock();
        //clear all data
        globalData.currentAthlete.clearJudgesVector(false);
        
        //enable buttons
        StartB.setEnabled(false);
        GroupGenderC.setEnabled(true);
        EventC.setEnabled(true);
        AthleteC.setEnabled(true);
        
    
        // disable buttons
        StopB.setEnabled(false);
        ShowB.setEnabled(false);
        EnterScore.setEnabled(false);
        ResetB.setEnabled(false);
        
        //head judge buttons and fields should be disabled
        Head1.setEnabled(false);
        HeadScore.setEnabled(false);
        HeadScore.setText("0.0");
        Head2.setEnabled(false);
        HeadDeduction.setEnabled(false);
        HeadDeduction.setText("0.0");
        Head3.setEnabled(false);
        Reason.setEnabled(false);
        Reason.setText("");
        HeadSubmitB.setEnabled(false);
        HeadUndoB.setEnabled(false);
        
        globalData.athleteActive=false;
        globalData.diffTime = 0;
        globalData.currentAthlete = null;
        
        globalData.releaseLock();
 
    }
    
    public void showSummary(boolean withScore)
    {
        //if the form doesn't exist create one
        if(finalSummary==null)
            finalSummary=new Summary(null, false);
        
        //make final summary visible
        if (finalSummary.isVisible() == false)
            finalSummary.setVisible(true);
        
        //clear previous data if any
        finalSummary.clear();
        
        finalSummary.setTitle(globalData.titleName);
        
        //add data to the form
        finalSummary.setGroupGender(globalData.currentGroup + ".  " + globalData.currentGender+"  "+globalData.currentAge);

        //set event
        if (globalData.currentEvent != null) 
            finalSummary.setEvent(globalData.currentEvent.getevent());

        //set athlete data
        if (globalData.currentAthlete != null) 
        {
            String temp = globalData.currentAthlete.getName();
            String name = temp.substring(0, temp.lastIndexOf('(') - 1);
            finalSummary.setName(name);
        }
        
        //set athlete score
        if (withScore) 
        {
            //bad hack to show scores from all judges
            if(globalData.scoringSystem==0)  // 0 Traditional System
            {
                finalSummary.setMistake(globalData.currentAthlete.getJudgesData(globalData.scoringSystem));
            }
            else if(globalData.scoringSystem==1)  //1 New Traditional System
            {
                finalSummary.setScoreA(globalData.currentAthlete.getAScore());
                finalSummary.setMistake(globalData.currentAthlete.MarshalAgreeA());            
            }
            else    // 2 Nandu System
            {
                finalSummary.setScoreA(globalData.currentAthlete.getAScore());
                finalSummary.setScoreC(globalData.currentAthlete.getCScore());
                //String test1=globalData.currentAthlete.MarshalAgreeA();
                //String test2=globalData.currentAthlete.MarshalAgreeC();
                finalSummary.setMistake(globalData.currentAthlete.MarshalAgreeA()+"\n"+globalData.currentAthlete.MarshalAgreeC());
            }
            int currentRanking=database.getRanking(globalData.currentAthlete,globalData.currentEvent.getevent(),globalData.currentAge,globalData.currentGroup,globalData.currentGender);
            finalSummary.setRank(""+currentRanking);
            finalSummary.setScoreB(globalData.currentAthlete.getBScore());
            finalSummary.setDeduction(globalData.currentAthlete.getDeductions(),globalData.currentAthlete.getReason());
            finalSummary.setFinalScore(globalData.currentAthlete.getFinalScore());
            
            
        }
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JComboBox AthleteC;
    private javax.swing.JButton EnterScore;
    private javax.swing.JComboBox EventC;
    private javax.swing.JMenuItem ExitM;
    private javax.swing.JButton GetScoresB;
    private javax.swing.JComboBox GroupGenderC;
    private javax.swing.JTextArea Head1;
    private javax.swing.JTextArea Head2;
    private javax.swing.JTextArea Head3;
    private javax.swing.JTextField HeadDeduction;
    private javax.swing.JTextField HeadScore;
    private javax.swing.JButton HeadSubmitB;
    private javax.swing.JButton HeadUndoB;
    private javax.swing.JCheckBoxMenuItem JudgeATimerM;
    private javax.swing.JPanel MainP;
    private javax.swing.JButton PublishB;
    private javax.swing.JTextField Reason;
    private javax.swing.JButton ResetB;
    private javax.swing.JButton ShowB;
    private javax.swing.JButton StartB;
    private javax.swing.JButton StopB;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JPanel jPanel6;
    private javax.swing.JPanel jPanel7;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JTextArea jTextArea1;
    // End of variables declaration//GEN-END:variables
    
}
